const fs = require('fs'); const path = require('path');
const chokidar = require('chokidar');

const mixinsFolder = '../pug/index.pug'
// 自动检查并更新index.pug的include
function updatePugIncludes() {
  const mixinDir = path.join(__dirname, '../../src/pug/mixins');
  let includes = []; // 将 includes 声明移到函数内部

  // 将 walk 函数移至内部并修复作用域问题
  const walk = (dir) => {
    fs.readdirSync(dir).forEach(file => {
      const filePath = path.join(dir, file);
      if (fs.statSync(filePath).isDirectory()) {
        walk(filePath);
      } else if (file.endsWith('.pug')) {
        // 使用当前作用域的 mixinDir
        includes.push(path.relative(mixinDir, filePath).replace(/\\/g, '/'));
      }
    });
  }

  console.log(mixinDir)

  // 新增目录创建逻辑（修复ENOENT错误）
  if (!fs.existsSync(mixinDir)) {
    fs.mkdirSync(mixinDir, { recursive: true });
    // 创建子目录结构
    // ['action', 'animate', 'client', 'media', 'complex', 'chain'].forEach(dir => {
    ['action', 'client', 'media', 'motion', 'chain', 'section'].forEach(dir => {
      fs.mkdirSync(path.join(mixinDir, dir), { recursive: true });
    });
  }
  const indexPath = path.join(__dirname, '../../src/pug/index.pug');
  const placeholder = '//- AUTO INCLUDES';

  let content = fs.existsSync(indexPath) ?
    fs.readFileSync(indexPath, 'utf8') :
    `${placeholder}\ndoctype html\nhtml\n    head\n        title Neo SVG Project\n    body\n        h1 Welcome to Neo SVG\n        `;

  // 清空旧include语句
  let newContent = content.split('\n')
    .filter(line => !line.startsWith('include mixins/'))
    .join('\n');

  // 插入新的include到占位符位置
  if (!newContent.includes(placeholder)) {
    newContent = newContent.replace(/(doctype html)/, `$1\n${placeholder}`);
  }

  const includesSet = new Set();
  walk(mixinDir);

  // 生成新的include语句（修复多余换行）
  let includesCode = [];
  includes.forEach(includePath => {
    const includeStatement = `include mixins/${includePath.replace('.pug', '')}`;
    if (!includesSet.has(includeStatement)) {
      includesCode.push(`${includeStatement}`); // 统一缩进
      includesSet.add(includeStatement);
    }
  });

  newContent = newContent.replace(placeholder, includesCode.join('\n')); // 使用数组join避免多余换行

  fs.writeFileSync(indexPath, newContent);
}

// 添加文件监控（在app.listen之前添加）
const watcher = chokidar.watch(path.join(__dirname, 'pug/mixins'), {
  ignored: /(^|[\/\\])\../, // 忽略隐藏文件
  persistent: true,
  ignoreInitial: true
});

watcher
  .on('add', updatePugIncludes)
  .on('unlink', updatePugIncludes);

// 递归查找所有.pug文件
let includes = []; // 确保在此处声明 includes 数组

// 递归查找所有.pug文件（修改为内部函数）
const walk = (dir) => {
  fs.readdirSync(dir).forEach(file => {
    const filePath = path.join(dir, file);
    if (fs.statSync(filePath).isDirectory()) {
      walk(filePath);
    } else if (file.endsWith('.pug')) {
      includes.push(path.relative(mixinDir, filePath).replace(/\\/g, '/'));
    }
  });
}

module.exports = updatePugIncludes;
